import requests
import os
from datetime import datetime


# 发送附件至数据库,返回文件id主键  上传的文件名格式：样品编号+测试项
async def upload(file) -> str:
    url = 'http://192.168.10.10:8000/ckapi/upload'
    # 确定上传文件与上传路径 文件名待定
    data = {'domainid': 10, 'file': file.filename}
    files = {file.filename: await file.read(), }
    response = requests.post(url, data=data, files=files).json()  # json格式
    file_id = response['data'].replace(';', '')
    print(file_id)
    return file_id


# upload()

# 传入需要查询的文件名 与上传成功返回的文件索引id 和凭证token,来获取项目名和订单号
async def get_task_item(c_names, c_indexs) -> dict:
    token = 'chenksoft!@!'  # 凭证token
    url = 'http://192.168.10.10:8000/ckapi/api/10/v2/updateTask.jsp'
    data = {'c_names': c_names,
            'c_indexs': c_indexs,
            "token": token}
    response = requests.post(url=url, data=data).json()
    task_item_dict = response['data'][0]
    print(task_item_dict)
    return task_item_dict


# get_task_item("Mt210119010-SEM.txt", 4)

# Mt210119010-SEM.txt 创建文件路径 与 日志路径
async def create_filepath(filename, task_item_dict) -> list:
    # root_path = 'D:\存储数据文件'
    root_path = r'D:\file_storage'
    file_text, subj = filename.split('-')[0], filename.split('-')[-1]
    year = '20' + file_text[2:4]  # 应该不会用到22世纪去吧 2021
    task = task_item_dict['c_tasknum']
    item = task_item_dict['c_itemnum']
    subj = subj.split('.')[0]
    # 判断数据文件存储位置,无则递归创建
    path = os.path.join(root_path, year, item, task, subj)
    log_path = os.path.join(root_path, year, item, 'logs.log')  # 项目文件夹下
    if not os.path.exists(path):
        os.makedirs(path)
    pathlist = [os.path.join(path, filename), log_path]
    return pathlist


async def store_file(file, pathlist):  # 存放文件 覆盖存入
    save_path, log_path = pathlist[0], pathlist[-1]
    with open(save_path, 'wb') as f:
        f.write(await file.read())
    now = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
    with open(log_path, 'a+') as log:
        logtext = now + file.filename + '存入'
        log.write(logtext)
    if os.path.exists(save_path):
        return True
    else:
        return False
